<template>
  <ul class="upload-imgs">
    <li v-if="(imgLen>=limit ? false : true)">
      <input type="file" class="upload" @change="addImg" ref="inputer" multiple/>
      <a class="add"><i class="iconfont icon-plus"></i><p>点击上传</p></a>
    </li>
    <li v-for='(value, key) in imgs' :key="key">
      <p class="img">
        <img :src="value.type.indexOf('image') !== -1?getObjectURL(value):'../../static/img/doc.png'">
        <a class="close" @click="delImg(key)">×</a>
      </p>
    </li>

  </ul>
</template>

<script>
export default {
  name: "MyUploadImgs",
  props: {
    fileTypes: {
      type: Array,
      default: () => ["jpeg", "bmp", "gif", "jpg"]
    },
    limit: {
      type: Number,
      default: 5
    },
    size: {
      type: Number,
      default: 5
    }
  },
  data() {
    return {
      imgs: {},
      imgLen: 0
    };
  },
  watch: {
    imgs: {
      handler(curVal) {
        this.$emit("imgs", curVal);
      },
      deep: true
    }
  },
  computed: {},
  methods: {
    addImg() {
      let inputDOM = this.$refs.inputer;
      // 通过DOM取文件数据
      this.fil = inputDOM.files;
      let oldLen = this.imgLen;
      let len = this.fil.length + oldLen;
      if (len > this.limit) {
        alert(
          "最多可上传" +
            this.limit +
            "张，您还可以上传" +
            (this.limit - oldLen) +
            "张"
        );
        return false;
      }

      for (let i = 0; i < this.fil.length; i++) {
        //判断文件大小
        let size = Math.floor(this.fil[i].size / 1024);
        if (size > this.size * 1024 * 1024) {
          alert("请选择" + this.size + "M以内的图片！");
          return false;
        }
        //判断文件类型
        let fileType = this.getFileType(this.fil[i].name);
        if (this.fileTypes != "" && this.fileTypes.indexOf(fileType) == -1) {
          alert("请选择" + this.fileTypes + "类型的图片！");
          return false;
        }

        this.imgLen++;
        this.$set(
          this.imgs,
          this.fil[i].name + "?" + new Date().getTime() + i,
          this.fil[i]
        );
      }
    },
    getObjectURL(file) {
      var url = null;
      if (window.createObjectURL != undefined) {
        // basic
        url = window.createObjectURL(file);
      } else if (window.URL != undefined) {
        // mozilla(firefox)
        url = window.URL.createObjectURL(file);
      } else if (window.webkitURL != undefined) {
        // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
      }
      return url;
    },
    getFileType(filePath) {
      var startIndex = filePath.lastIndexOf(".");
      if (startIndex != -1)
        return filePath
          .substring(startIndex + 1, filePath.length)
          .toLowerCase();
      else return "";
    },
    delImg(key) {
      this.$delete(this.imgs, key);
      this.imgLen--;
    }
  }
};
</script>
